<template>
  <div class="box" v-loading="loading">
    <el-empty class="cenetr" v-if="show" description="暂无数据" />
    <div ref="main" class="box"></div>
  </div>
</template>

<script>
import * as echarts from 'echarts';
export default {
  props: {
    loading: {
      type: Boolean,
      default: false
    },
    title: {
      type: String,
      default: '图标标题'
    },
    data: {
      type: Array,
      default: () => []
    }
  },
  computed: {
    show() {
      const { series } = this.$attrs;
      if (this.data) return !this.data?.length;
      if (series) return !series?.length;
      return true;
    }
  },
  data() {
    return {
      option: {
        title: {
          top: '0',
          left: 'center',
          text: this.title,
          textStyle: { fontWeight: 'normal' }
        },
        legend: { top: 'bottom' },
        tooltip: { trigger: 'item' },
        grid: {
          top: '40px',
          left: '0',
          right: '10px',
          bottom: '50px',
          containLabel: true
        }
      },
      mychart: null
    };
  },
  watch: {
    data() {
      this.updateChart();
    }
  },
  mounted() {
    this.mychart = echarts.init(this.$refs.main);
    this.updateChart();
  },
  methods: {
    updateChart() {
      const { type, color } = this.$attrs;
      if (type === 'pie') {
        this.canvatPieData();
      } else if (type === 'bar') {
        this.canvatBarData();
      } else {
        for (let key in this.$attrs) {
          this.option[key] = this.$attrs[key];
        }
      }
      if (color) this.option.color = color;
      this.mychart.setOption(this.option);
    },
    canvatBarData() {
      const { xAxis, yAxis, field = [{ key: 'value' }] } = this.$attrs;
      const axis = {
        type: 'category',
        axisTick: { alignWithLabel: true },
        data: this.data.map(i => i[xAxis || yAxis])
      };
      if (xAxis) {
        this.option.xAxis = axis;
        this.option.yAxis = { type: 'value' };
      } else if (yAxis) {
        this.option.yAxis = axis;
        this.option.xAxis = { type: 'value' };
      }
      this.option.series = field.map(({ key, ...style }) => {
        return { type: 'bar', ...style, data: this.data.map(i => i[key]) };
      });
    },
    canvatPieData() {
      const options = {
        type: 'pie',
        itemStyle: {
          borderColor: '#fff',
          borderRadius: 6,
          borderWidth: 2
        },
        radius: ['40%', '70%'],
        center: ['50%', '47%'],
        data: this.data,
        avoidLabelOverlap: false
      };
      for (let key in this.$attrs) {
        options[key] = this.$attrs[key];
      }
      this.option.series = [options];
    }
  }
};
</script>

<style scoped>
.box {
  height: 100%;
  position: relative;
}
.cenetr {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
}
</style>
